package com.besall.allbase.view.activity.chipstoollevel4.customerdial.makedial;

import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_PATH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER_CACHE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_FOLDER_CACHE_PHOTO_NAME;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bes.bessdk.utils.SPHelper;
//import bb.lanxing.R;
import bb.lanxing.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CropPhotoActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener, TextWatcher {

    CropPhotoBgView crop_photo_bg;
    ImageView crop_photo_image;

    RadioGroup form_radio_group;
    TextView cur_data_name_0, crop_photo_symbol, cur_data_name_1;
    EditText cur_data_0, cur_data_1;
    Button crop_photo_save_setting;

    Button button_cancel;
    Button button_sure;

    private int sx;
    private int sy;
    private float imageW;
    private float imageH;

    String takePhotoPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cropphoto);

        form_radio_group = (RadioGroup) findViewById(R.id.form_radio_group);
        form_radio_group.setOnCheckedChangeListener(this);
        cur_data_name_0 = (TextView) findViewById(R.id.cur_data_name_0);
        crop_photo_symbol = (TextView) findViewById(R.id.crop_photo_symbol);
        cur_data_name_1 = (TextView) findViewById(R.id.cur_data_name_1);
        cur_data_0 = (EditText) findViewById(R.id.cur_data_0);
        cur_data_0.addTextChangedListener(this);
        cur_data_1 = (EditText) findViewById(R.id.cur_data_1);
        cur_data_1.addTextChangedListener(this);

        crop_photo_save_setting = (Button) findViewById(R.id.crop_photo_save_setting);
        crop_photo_save_setting.setOnClickListener(this);
        crop_photo_bg = (CropPhotoBgView) findViewById(R.id.crop_photo_bg);
        crop_photo_image = (ImageView) findViewById(R.id.crop_photo_image);
        int photoForm = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE);
        int length = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE);
        cur_data_0.setText(length + "");
        int width = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE);
        cur_data_1.setText(width + "");
        refreshUI(photoForm);

        takePhotoPath = new com.besall.allbase.common.utils.FileUtils(this).getFilesDir(CUSTOMER_DIAL_FOLDER_CACHE_PHOTO_NAME, CUSTOMER_DIAL_FOLDER_CACHE);
        Bitmap bitmap = loadBitmap(takePhotoPath, true);
        crop_photo_image.setImageBitmap(bitmap);
        crop_photo_image.setOnTouchListener(this);

        button_cancel = (Button) findViewById(R.id.button_cancel);
        button_cancel.setOnClickListener(this);
        button_sure = (Button) findViewById(R.id.button_sure);
        button_sure.setOnClickListener(this);

        crop_photo_save_setting.setVisibility(View.GONE);
    }

    private void refreshUI(int photoForm) {
        if (photoForm == 2) {
            SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, 2);
            form_radio_group.check(R.id.form_square);
            cur_data_name_0.setText(getText(R.string.crop_photo_data_name_length));
            crop_photo_symbol.setVisibility(View.VISIBLE);
            cur_data_1.setVisibility(View.VISIBLE);
            cur_data_name_1.setVisibility(View.VISIBLE);
        } else {
            SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, 1);
            form_radio_group.check(R.id.form_circle);
            cur_data_name_0.setText(getText(R.string.crop_photo_data_name_diameter));
            crop_photo_symbol.setVisibility(View.GONE);
            cur_data_1.setVisibility(View.GONE);
            cur_data_name_1.setVisibility(View.GONE);
        }
    }

    public static Bitmap loadBitmap(String imgpath) {
        return BitmapFactory.decodeFile(imgpath);
    }

    public static Bitmap loadBitmap(String imgPath, boolean adjustOritation) {
        if (!adjustOritation) {
            return loadBitmap(imgPath);
        } else {
            Bitmap bm = loadBitmap(imgPath);
            int digree = 0;
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(imgPath);
            } catch (IOException e) {
                e.printStackTrace();
                exif = null;
            }
            if (exif != null) {
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                    default:
                        digree = 0;
                        break;
                }
            }
            if (digree != 0) {
                Matrix m = new Matrix();
                m.postRotate(digree);
                bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            }
            return bm;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {


        if(v.getId() == R.id.crop_photo_image){
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    sx = (int) event.getRawX();
                    sy = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int x = (int) event.getRawX();
                    int y = (int) event.getRawY();
                    int dx = x - sx;
                    int dy = y - sy;
                    if (dx > 5 || dy > 5) {
                        sx = (int) event.getRawX();
                        sy = (int) event.getRawY();
                    }
                    int l = crop_photo_image.getLeft();
                    int r = crop_photo_image.getRight();
                    int t = crop_photo_image.getTop();
                    int b = crop_photo_image.getBottom();
                    int newL = l + dx;
                    if (newL < - 300) {
                        return false;
                    }
                    int newR = r + dx;
                    if (newR > v.getWidth() + 300) {
                        return false;
                    }
                    int newT = t + dy;
                    if (newT < - 300) {
                        return false;
                    }
                    int newB = b + dy;
                    if (newB > v.getHeight() + 600) {
                        return false;
                    }
                    crop_photo_image.layout(newL, newT, newR, newB);
                    break;
                default:
                    break;
            }
        }
        /*
        switch (v.getId()) {
            case R.id.crop_photo_image:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        sx = (int) event.getRawX();
                        sy = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int x = (int) event.getRawX();
                        int y = (int) event.getRawY();
                        int dx = x - sx;
                        int dy = y - sy;
                        if (dx > 5 || dy > 5) {
                            sx = (int) event.getRawX();
                            sy = (int) event.getRawY();
                        }
                        int l = crop_photo_image.getLeft();
                        int r = crop_photo_image.getRight();
                        int t = crop_photo_image.getTop();
                        int b = crop_photo_image.getBottom();
                        int newL = l + dx;
                        if (newL < - 300) {
                            return false;
                        }
                        int newR = r + dx;
                        if (newR > v.getWidth() + 300) {
                            return false;
                        }
                        int newT = t + dy;
                        if (newT < - 300) {
                            return false;
                        }
                        int newB = b + dy;
                        if (newB > v.getHeight() + 600) {
                            return false;
                        }
                        crop_photo_image.layout(newL, newT, newR, newB);
                        break;
                    default:
                        break;
                }
                break;
        }*/
        return true;
    }

    public Bitmap toRectBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Log.i("TAG", "toRectBitmap: ------" + width);
        Log.i("TAG", "toRectBitmap: ------" + height);
        int curLength = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE);
        int curWidth = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE);

        int cavasW = curWidth * 3 - 60;
        int cavasH = curLength * 3 - 60;
        Bitmap output = Bitmap.createBitmap(cavasW * 2, cavasH * 2, Bitmap.Config.RGB_565);
//        Bitmap output = Bitmap.createBitmap(cavasW * 2, cavasH * 2, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        paint.setAntiAlias(true);// 设置画笔无锯齿
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        imageW = wm.getDefaultDisplay().getWidth();
        imageH = imageW * height / width;

        float cx = width / 2 - crop_photo_image.getLeft() * width / imageW;
        float cy = height / 2 - crop_photo_image.getTop() * height / imageH;
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
        Rect mSrcRect, mDstRect;
        mSrcRect = new Rect((int) (cx - cavasW), (int) (cy - cavasH), (int) (cx + cavasW), (int) (cy + cavasH));
        mDstRect = new Rect(0, 0, cavasW * 2, cavasH * 2);
        canvas.drawBitmap(bitmap, mSrcRect, mDstRect, paint);
        return output;
    }

    private Bitmap getCircleBitmap(Bitmap source) {
        if (source == null) return null;
        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
        Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(getColor(R.color.white));
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    private Bitmap getFixedResolutionBitmap(Bitmap bitmap, int width, int height) {
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        paint.setAntiAlias(true);// 设置画笔无锯齿
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
        Rect mSrcRect, mDstRect;
        mSrcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        mDstRect = new Rect(0, 0, width, height);
        canvas.drawBitmap(bitmap, mSrcRect, mDstRect, paint);

//        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
//        Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
//        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
//        int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
//        if (heightRatio > 1 || widthRatio > 1) {
//            if (heightRatio > widthRatio) {
//                bmpFactoryOptions.inSampleSize = heightRatio;
//            } else {
//                bmpFactoryOptions.inSampleSize = widthRatio;
//            }
//        }
//        bmpFactoryOptions.inJustDecodeBounds = false;
//        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
        return output;

    }

    private void saveBitmap(Bitmap bitmap, String picPath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(picPath));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {


        if(v.getId() == R.id.crop_photo_save_setting){
            if (cur_data_0.getText().length() == 0 || cur_data_1.getText().length() == 0) {
                return;
            }
            int photoForm = form_radio_group.getCheckedRadioButtonId() == R.id.form_square ? 2 : 1;
            SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, Integer.valueOf(cur_data_0.getText().toString()));
            if (photoForm == 2) {
                SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, Integer.valueOf(cur_data_1.getText().toString()));
            } else {
                SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, Integer.valueOf(cur_data_0.getText().toString()));
            }
            SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, photoForm);
            crop_photo_bg.invalidate();
            crop_photo_save_setting.setVisibility(View.GONE);
        }else if(v.getId() == R.id.button_cancel){
            finish();

        }else if(v.getId() == R.id.button_sure){
            Bitmap bitmap = loadBitmap(takePhotoPath, true);
            Bitmap bitmapAf = toRectBitmap(bitmap);
            int curLength = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE);
            int curWidth = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE);
            Bitmap newBitmap = getFixedResolutionBitmap(bitmapAf, curWidth, curLength);
            Log.i("TAG", "onClick: -----------" + newBitmap.getHeight());
            Log.i("TAG", "onClick: -----------" + newBitmap.getWidth());
            crop_photo_image.setImageBitmap(bitmapAf);
            String path = new com.besall.allbase.common.utils.FileUtils(this).getFilesDir(DateFormat.format("MM-dd-HH:mm:ss:sss", System.currentTimeMillis()) + ".png", CUSTOMER_DIAL_FOLDER);
            int photoForm1 = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE);
            if (photoForm1 == 2) {
                saveBitmap(newBitmap, path);
            } else {
                saveBitmap(getCircleBitmap(newBitmap), path);
            }
            if (path != null) {
                try {
                    String outPath = path.replace(".png", ".png");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            Intent intent = new Intent();
            intent.putExtra(CUSTOMER_DIAL_CROP_PHOTO_PATH_KEY, path);
            setResult(RESULT_OK, intent);
            finish();
        }

        /*
        switch (v.getId()) {
            case R.id.crop_photo_save_setting:
                if (cur_data_0.getText().length() == 0 || cur_data_1.getText().length() == 0) {
                    return;
                }
                int photoForm = form_radio_group.getCheckedRadioButtonId() == R.id.form_square ? 2 : 1;
                SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, Integer.valueOf(cur_data_0.getText().toString()));
                if (photoForm == 2) {
                    SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, Integer.valueOf(cur_data_1.getText().toString()));
                } else {
                    SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, Integer.valueOf(cur_data_0.getText().toString()));
                }
                SPHelper.putPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, photoForm);
                crop_photo_bg.invalidate();
                crop_photo_save_setting.setVisibility(View.GONE);
                break;
            case R.id.button_cancel:
                finish();

                break;
            case R.id.button_sure:
                Bitmap bitmap = loadBitmap(takePhotoPath, true);
                Bitmap bitmapAf = toRectBitmap(bitmap);
                int curLength = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_LENGTH_VALUE);
                int curWidth = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_KEY, CUSTOMER_DIAL_CROP_PHOTO_WIDTH_VALUE);
                Bitmap newBitmap = getFixedResolutionBitmap(bitmapAf, curWidth, curLength);
                Log.i("TAG", "onClick: -----------" + newBitmap.getHeight());
                Log.i("TAG", "onClick: -----------" + newBitmap.getWidth());
                crop_photo_image.setImageBitmap(bitmapAf);
                String path = new com.besall.allbase.common.utils.FileUtils(this).getFilesDir(DateFormat.format("MM-dd-HH:mm:ss:sss", System.currentTimeMillis()) + ".png", CUSTOMER_DIAL_FOLDER);
                int photoForm1 = (int) SPHelper.getPreference(this, CUSTOMER_DIAL_CROP_PHOTO_FORM_KEY, CUSTOMER_DIAL_CROP_PHOTO_FORM_VALUE);
                if (photoForm1 == 2) {
                    saveBitmap(newBitmap, path);
                } else {
                    saveBitmap(getCircleBitmap(newBitmap), path);
                }
                if (path != null) {
                    try {
                        String outPath = path.replace(".png", ".png");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                Intent intent = new Intent();
                intent.putExtra(CUSTOMER_DIAL_CROP_PHOTO_PATH_KEY, path);
                setResult(RESULT_OK, intent);
                finish();

                break;
            default:
                break;
        }*/
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        if(checkedId == R.id.form_square){
            crop_photo_save_setting.setVisibility(View.VISIBLE);
            refreshUI(2);
        }else if(checkedId == R.id.form_circle){
            crop_photo_save_setting.setVisibility(View.VISIBLE);
            refreshUI(1);
        }

/*        switch (checkedId) {
            case R.id.form_square:
                crop_photo_save_setting.setVisibility(View.VISIBLE);
                refreshUI(2);
                break;
            case R.id.form_circle:
                crop_photo_save_setting.setVisibility(View.VISIBLE);
                refreshUI(1);
                break;
            default:
                break;
        }*/
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        crop_photo_save_setting.setVisibility(View.VISIBLE);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
